import { addChatDataCache, getUserId } from "@/utils/app";
import { Notify } from "vant";

export let ws: WebSocket | undefined = undefined

export const WebSocketInit = () => {
  ws = new WebSocket("ws://127.0.0.1:9002/ws");
  ws.onopen = (evt) => {
    Notify({ type: "success", message: "服务器连接成功" });
    sendMessage({
      type: MessageActionType.CONNECT,
      data: getUserId(),
    });
  };
  ws.onerror = (evt) => {
    Notify({ type: "danger", message: "服务器连接失败，请刷新重试" });
  };
  ws.onclose = function (evt) {
    console.log("WebSocketClosed!");
  };
  ws.onmessage = function (evt) {

    const msg: Message = JSON.parse(evt.data)

    if (msg.type == MessageActionType.CHAT) {
      strategy.chat(msg.data)
      //缓存聊天信息
      addChatDataCache(msg.data)
    } else if (msg.type == MessageActionType.SIGNED) {
      //消息签收


    }
  };

}



export const MessageActionType = {
  CONNECT: 1, //客户端连接
  CHAT: 2, //聊天
  SIGNED: 3, //签收聊天信息
  EEPALIVE: 4, //心跳
  PULL_FRIEND: 5 //拉取好友列表
}

type Message = {
  type: number,
  data: any
}

// 处理信息逻辑
export const chatMessageStrategy = (message: ChatMessage) => {
  console.log('receive message default strategy');

}


class MessageStrategy {
  public chat(message: ChatMessage) {
    console.log('chat默认实现');
  }
  public signed(message: SignedMessage) {
    console.log("signed默认实现");

  }
}
export const strategy = new MessageStrategy()

export const sendMessage = (msg: Message) => {
  if (ws) {
    ws.send(JSON.stringify(msg))
  }
}

export type ChatMessage = {
  sendUserId: string,
  acceptUserId: string,
  msg: string
}

export type SignedMessage = {
  msgId: string
}

export const sendChatMessage = (msg: ChatMessage) => {
  sendMessage({
    type: MessageActionType.CHAT,
    data: msg
  })
}



